<?php
namespace Modules\Activity\Http\Controllers\Admin\Choushang;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use \Modules\Activity\Entities\Choushang\Activity;

use Validator;
use ThrowException;
use DB;

class ActivityController extends Controller
{
    public function index(Request $req)
    {
        $options = $req->all();
        $w = '';

        $per_page = 100;
        if ( isset($options['per_page']) && $options['per_page'] > 0 ){
            $per_page = $options['per_page'];
        }

        $page = 0;
        if ( isset($options['page']) && $options['page'] > 0 ){
            $page = $options['page']-1;
        }

        $offset = $page * $per_page;

        if ( isset($options['status']) && $options['status'] == 'sell_out' ){
            $w = " and a.stock = 0 ";
        }
        if ( isset($options['status']) && $options['status'] == 'off_stock' ){
            $w = " and a.stock > 0 and a.status = 0 ";
        }
        if ( isset($options['status']) && $options['status'] == 'on_stock' ){
            $w = " and a.stock > 0 and a.status = 1 ";
        }

        if ( isset($options['key']) && $options['key'] ){
            $w .= " and a.title like '%{$options['key']}%' ";
        }

        if ( isset($options['ids']) && $options['ids'] ){
            $w .= " and a.title IN (select title from choushang_activity where id in (".implode(',', $options['ids']).") ) ";
        }

        $db = "choushang_activity a left join choushang_skus b on a.id = b.activity_id";
        $field = "a.title, a.money_price, sum(a.stock) stock, sum(b.sales) sales, count(distinct a.id) cnt, max(a.created_at) created_at
                , min(a.thumb) thumb, a.status, max(a.id) id, max(a.uuid) uuid, max(play_type) play_type, max(a.list_weight) list_weight";
        $res = DB::select("select $field from $db where 1 $w group by a.title, a.money_price, a.status order by list_weight desc, created_at desc limit $per_page offset $offset ");

        $total_res = DB::select(" select count(*) cnt from ( select distinct a.title from $db where 1 $w group by a.title, a.money_price, a.status ) c ");

        if ( count($res) == 0 ){
            $res_ = [
                'current_page' => $page,
                'item_total' => 1,
                'list' => [],
            ];
        }else{
            $total_res = object_to_array($total_res);

            $res = object_to_array($res);
            $res_ = [
                'current_page' => $page+1,
                'item_total' => $total_res[0]['cnt'],
                'list' => $res,
            ];
        }

        return json_encode($res_);
    }


    public function getCnt(Request $req)
    {
        $options = $req->all();
        $w = '';
        if ( isset($options['key']) && $options['key'] ){
            $w = " and title like '%{$options['key']}%' ";
        }
        $res = DB::select("select count(distinct title) cnt, status from choushang_activity where 1 $w and stock > 0 group by status ");
        $res_no_stock = DB::select("select count(distinct title) cnt, '0' status from choushang_activity where 1 $w and stock = 0 ");

        if ( count($res) == 0 ){
            $total = [
                'on_stock' => 0,
                'off_stock' => 0
            ];
        }else{
            $res = array_column(object_to_array($res), 'cnt', 'status');
            $total = [
                'on_stock' => isset($res[1]) && $res[1] ? $res[1] : 0,
                'off_stock' => isset($res[0]) && $res[0] ? $res[0] : 0
            ];
        }

        if ( count($res_no_stock) == 0 ){
            $total['sell_out'] = 0;
        }else{
            $no_stock = array_column(object_to_array($res_no_stock), 'cnt', 'status');
            $total['sell_out'] = $no_stock[0];
        }

        return [
            'total' => $total
        ];
    }

    public function getList(Request $req)
    {
        $options = $req->all();

        $options['order_by'] = ['id' => 'asc'];
        $options['with_count'] = ['skus', 'last_skus'];
//        $options['with'] = ['choushang_last_skus'];

        if ( isset($options['title']) && $options['title'] ){
            $options['where'] = ['title' => $options['title']];
        }
        $options['order_by'] = ['list_weight' => 'desc'];


        $list = Activity::getList($options);

        $list->each(function ($item) {
            $item->sku_stock = $item->skus->sum('stock');
            $item->last_sku_stock = $item->last_skus->sum('stock');
        });

        return $list->generateListResponse();
    }


    public function show(Request $req, $uuid)
    {
        // 
        $item = Activity::getEntity([
            'uuid' => $uuid
        ]);

        $info = $item->getInfo();

        return [
            'info' => $info
        ];
    }

    public function store(Request $req)
    {
        $rule = [
            'title' =>  ['required'],
            'stock' => ['required']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $info = $req->all();

        DB::beginTransaction();

        $item = Activity::create($info);

        DB::commit();

        return [
            'id' => $item->id,
            'uuid' => $item->uuid
        ];
    }

    public function update(Request $req, $uuid)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $item = Activity::getEntity([
            'uuid' => $uuid
        ]);

        DB::beginTransaction();

        if ($req->type === 'update') {
            $info = $req->input('attributes');

            $item->update($info);
        }elseif ($req->type === 'copy') {
            $item->copy();
        }

        DB::commit();

        return [];
    }

    public function destroy(Request $req, $uuid)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $item = Activity::getEntity([
            'uuid' => $uuid
        ]);

        $item->delete();

        return [];
    }

    public function doPatch(Request $req, $type)
    {
        $options = $req->all();
        $title = $options['title'];

        if ( $type == 'update' ){
            $title = $options['title_old'];
            $arr = [
                'title',
                'thumb',
                'image_3d',
                'money_price',
                'score_price',
                'stock',
                'sales',
                'rules',
                'status',
                'last_open_time_set',
                'play_type',
                'list_weight',
                'share_rule',
                'is_share_enabled',
                'is_invite_enabled',
                'invite_rule',
            ];
            foreach ( $options as $k => $v ){
                if ( !in_array($k, $arr) ) unset($options[$k]);
                if ( in_array($k, ['is_share_enabled', 'is_invite_enabled']) ){
                    $options[$k] = in_array($v, ['false', '0']) ? 0 : 1;
                }
            }
            DB::table('choushang_activity')->where('title', '=', $title)->update($options);
        }
        if ( $type == 'delete' ){
            DB::table('choushang_activity')->where('title', '=', $title)->delete();
        }
        return [];
    }

    public function off_stock_all()
    {
        DB::beginTransaction();
        DB::table('choushang_activity')->update(['status'=>0]);
        DB::commit();

        return [];
    }

    public function copy_more(Request $req, $uuid)
    {
        ini_set("memory_limit",'-1');
        ini_set('max_execution_time', 600);
        set_time_limit(0);
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        while (1){
            if ( $req->nums <= 0 ) break;
            $nums = min($req->nums, 200);
            self::copy_more_($uuid, $nums);
            $req->nums -= 200;
        }

        return [];
    }

    public function copy_more_($uuid, $nums)
    {
        DB::beginTransaction();

        $item_r = DB::table('choushang_activity')->where('uuid', $uuid)->first();
        $uuid_arr = array();
        $act_init = object_to_array($item_r);
        $act_init['stock'] += $act_init['sales'];
        $act_init['sales'] = 0;
        $act_arr = array();
        $time = date('Y-m-d H:i:s');

        for ( $i=0; $i<$nums; $i++ ){
            $a_uuid = uniqid();
            array_push($uuid_arr, $a_uuid);
            $act_arr[$i] = $act_init;
            $act_arr[$i]['uuid'] = $a_uuid;
            $act_arr[$i]['created_at'] = $time;
            $act_arr[$i]['updated_at'] = $time;
            unset($act_arr[$i]['id']);
        }
        DB::table('choushang_activity')->insert($act_arr);

        $id_obj = DB::table('choushang_activity')->whereIn('uuid', $uuid_arr)->get()->toArray();
        $id_arr = array_column($id_obj, 'id');

        $sku_r = DB::table('choushang_skus')->where('activity_id', $item_r->id)->get()->toArray();
        $sku_arr = array();
        $index_sku = 0;
        foreach ( $id_arr as $k => $v ){
            foreach ( $sku_r as $sk => $sv ){
                $a_uuid = uniqid();
                $sku_arr[$index_sku] = object_to_array($sv);
                $sku_arr[$index_sku]['stock'] = $sv->sales + $sv->stock;
                $sku_arr[$index_sku]['sales'] = 0;
                $sku_arr[$index_sku]['activity_id'] = $v;
                $sku_arr[$index_sku]['uuid'] = $a_uuid;
                $sku_arr[$index_sku]['created_at'] = $time;
                $sku_arr[$index_sku]['updated_at'] = $time;
                unset($sku_arr[$index_sku]['id']);
                $index_sku++;
            }
        }
        DB::table('choushang_skus')->insert($sku_arr);
        unset($sku_arr);
        unset($sku_r);

        $sku_r = DB::table('choushang_last_skus')->where('activity_id', $item_r->id)->get()->toArray();
        $sku_arr = array();
        $index_sku = 0;
        foreach ( $id_arr as $k => $v ){
            foreach ( $sku_r as $sk => $sv ){
                $a_uuid = uniqid();
                $sku_arr[$index_sku] = object_to_array($sv);
                $sku_arr[$index_sku]['stock'] = $sv->sales + $sv->stock;
                $sku_arr[$index_sku]['sales'] = 0;
                $sku_arr[$index_sku]['activity_id'] = $v;
                $sku_arr[$index_sku]['uuid'] = $a_uuid;
                $sku_arr[$index_sku]['created_at'] = $time;
                $sku_arr[$index_sku]['updated_at'] = $time;
                unset($sku_arr[$index_sku]['id']);
                $index_sku++;
            }
        }

        DB::table('choushang_last_skus')->insert($sku_arr);

        DB::commit();

        return true;
    }

    public function copy_one(Request $req, $uuid)
    {
        $rule = [
        ];

        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $item = Activity::getEntity([
            'uuid' => $uuid
        ]);

        $info = $item->getInfo([
            'image_3d',
            'invite_rule',
            'is_invite_enabled',
            'min_lucky_score',
            'money_price',
            'score_price',
            'multi_buy_discount',
            'tags',
            'thumb',
            'title',
            'stock',
            'last_open_time_set',
            'rules',
            'play_type',
            'sku_level'
        ]);
        $info['status'] = 0;
        $info['title'] .= '-副本';

        $newItem = Activity::create($info);
        $skuArray = [];
        foreach ($item->skus as $sku) {
            if ( $sku->sales > 0 )
                $sku->stock = $sku->stock + $sku->sales;

            $skuInfo = $sku->getInfo([
                'activity_id',
                'sku_type',
                'assets',
                'product_id',
                'title',
                'number',
                'thumb',
                'money_price',
                'score_price',
                'stock',
                'odds',
                'level',
                'list_weight',
                'status',
                'is_resaleable',
                'display_money_price',
                'discount_score_price',
                'detail_images',
                'return_sale_ratio',
                'use_lucky_score'
            ]);

            $skuInfo['uuid'] = uniqid();

            array_unshift($skuArray, $skuInfo);
        }

        $lastSkuArray = [];
        foreach ($item->last_skus as $sku) {
            $sku->stock = $sku->stock + $sku->sales;

            $lastSkuInfo = $sku->getInfo([
                'activity_id',
                'sku_type',
                'assets',
                'product_id',
                'title',
                'number',
                'thumb',
                'money_price',
                'score_price',
                'stock',
                'odds',
                'level',
                'list_weight',
                'status',
                'is_resaleable',
                'display_money_price',
                'discount_score_price',
                'detail_images',
                'return_sale_ratio',
                'use_lucky_score'
            ]);

            $lastSkuInfo['uuid'] = uniqid();

            array_unshift($lastSkuArray, $lastSkuInfo);
        }

        $newItem->skus()->createMany($skuArray);
        $newItem->last_skus()->createMany($lastSkuArray);


        return [];
    }

    public function copy_main(Request $req, $uuid)
    {
        $rule = [
        ];

        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $item = Activity::getEntity([
            'uuid' => $uuid
        ]);

        $info = $item->getInfo([
            'image_3d',
            'invite_rule',
            'is_invite_enabled',
            'min_lucky_score',
            'money_price',
            'multi_buy_discount',
            'tags',
            'thumb',
            'title',
            'stock',
            'sku_level'
        ]);
        $info['status'] = 1;
        $info['title'] .= '-复制';

        $newItem = Activity::create($info);
        $skuArray = [];
        foreach ($item->skus as $sku) {
            $sku->stock = $sku->sales = 0;
            $skuInfo = $sku->getInfo([
                'activity_id',
                'sku_type',
                'assets',
                'product_id',
                'title',
                'number',
                'thumb',
                'money_price',
                'score_price',
                'stock',
                'odds',
                'level',
                'list_weight',
                'status',
                'is_resaleable',
                'display_money_price',
                'discount_score_price',
                'detail_images',
                'return_sale_ratio',
                'use_lucky_score'
            ]);

            $skuInfo['uuid'] = uniqid();

            array_unshift($skuArray, $skuInfo);
        }

        $lastSkuArray = [];
        foreach ($item->last_skus as $sku) {
            $sku->stock = $sku->sales = 0;

            $lastSkuInfo = $sku->getInfo([
                'activity_id',
                'sku_type',
                'assets',
                'product_id',
                'title',
                'number',
                'thumb',
                'money_price',
                'score_price',
                'stock',
                'odds',
                'level',
                'list_weight',
                'status',
                'is_resaleable',
                'display_money_price',
                'discount_score_price',
                'detail_images',
                'return_sale_ratio',
                'use_lucky_score'
            ]);

            $lastSkuInfo['uuid'] = uniqid();

            array_unshift($lastSkuArray, $lastSkuInfo);
        }

        $newItem->skus()->createMany($skuArray);
        $newItem->last_skus()->createMany($lastSkuArray);

        return [];
    }


}
